import grails.converters.JSON
import grails.converters.deep.XML
import java.util.*;

class MassLookupController {

  /**
   * does the actual converting of data
   */
  ConvertService convertService

  def index =
  {
    return [fromFields:convertService.getFromConversions(),toFields:convertService.toConversions]
  }

  def masstransform =
  {

    String from = params.from
    def StrTo = params.to
    String ids = params.ids

    assert from != null, "please provide a from parameter"
//    assert StrTo != null, "please provide a to parameter"
//    assert ids != null, "please provide an ids parameter"

    if( ids == null || ids.trim().length() == 0 )
    {
      flash.message = "Error! Ids parameter is mandatory, Please Enter some ids."
      redirect(action:"index")
    }else
    if( StrTo == null )
    {
      flash.message = "Error! To parameter is mandatory, Please selcect at least one." 
      redirect(action:"index")
    }

    def to = []

    if( StrTo instanceof String )
    {
       to.add StrTo.trim()
    }else
    {
       StrTo.each {String s ->
           to.add s.trim()
        }

    }

    // prepare the list of ids : Start
    def list = []
    ids.split("\n").each {String s ->
      list.add s.trim()
    }
    // prepare the list of ids : End

    //call the service to conver the data
    Collection<Map<Compound,?>> result =  convertService.convert(from, to, list)

    //decide which modus we use for deployment
    if (params.format != null) {
      if (params.format == 'xml') {
        render result as XML
      }
      else if (params.format == 'json') {
        render result as JSON

      }
      else {
         return [transform:result,ids:list,from:from,to:to]
      }
    }
    else {
      return [transform:result,ids:list,from:from,to:to]
    }

  }

  /**
   * returns the provide formats
   */
  static List getFormats() {
    return ['xml', 'json']
  }

}
